﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;

namespace Luka;

public static class JwtBearerSetup
{
    /// <summary>
    /// 添加 Jwt Bearer
    /// </summary>
    /// <param name="services"></param>
    /// <returns></returns>
    public static IServiceCollection AddJwt(this IServiceCollection services)
    {
        // 添加加密解密服务
        services.AddSingleton<IJwtBearerService, JwtBearerService>();
        // 注册Jwt验证提供器实现类
        var handler = InternalApp.TypeList.FirstOrDefault(f => typeof(IJwtBearerHandler).IsAssignableFrom(f) && !f.IsInterface);
        if (handler != null)
        {
            services.AddSingleton(typeof(IJwtBearerHandler), handler);
        }
        // 注册策略授权处理程序
        services.TryAddSingleton<IAuthorizationHandler, AuthorizationHandler>();
        //启用全局授权
        services.AddFilter<AuthorizeFilter>();
        // 添加默认授权
        var authenticationBuilder = services.AddAuthentication(options =>
        {
            options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
            options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        }).AddJwtBearer(options =>
        {
            options.TokenValidationParameters = Penetrates.GetJwtOptions().Parameters;
        });
        return services;
    }
}